package com.htht.smartschool.common.job;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.io.IOUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.htht.smartschool.model.card.TFamilyphone;
import com.htht.smartschool.service.card.CardService;
import com.htht.smartschool.util.redis.RedisKeyConstant;
import com.htht.smartschool.util.redis.RedisUtil;
import com.htht.smartschool.util.system.ConfigUtil;
import com.htht.smartschool.util.system.DateUtil;
import com.htht.smartschool.util.system.Freemark;
import com.htht.smartschool.util.system.FtpUtil;
import com.htht.smartschool.util.system.GsonUtils;

public class UpFileJob implements Job {
	CardService cs = new CardService();

	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		List<TFamilyphone> result = getPhonelist();
		Set<TFamilyphone> ts = new HashSet<TFamilyphone>();
		ts.addAll(result);
		List<TFamilyphone> list = new ArrayList<TFamilyphone>();
		list.addAll(ts);
		if (list.size() > 0) {
			String f = Freemark.class.getResource("/").getPath();
			File file = new File(f);
			Freemark freemark = new Freemark(new File(file.getPath()
					+ "/template/"));
			Date time = new Date();
			String filename = "QQHM_XXK_"
					+ DateUtil.getFormatDate(time, "yyyyMMdd") + "_0001.0001";
			freemark.setTemplateName("familynums.ftl");
			freemark.setFileName(filename);
			freemark.setFilePath(ConfigUtil.getProperty("ftp", "uploads"));
			// 生成word
			freemark.createFile(list);
			upload();
		} else {
			System.out.println("今日无人修改亲情号码，无需上传！");
		}

	}

	// public static void main(String[] args) {
	// List<TFamilyphone> list = new ArrayList<TFamilyphone>();
	// TFamilyphone tp = new TFamilyphone();
	// tp.setOperation("2");
	// tp.setFamilyphone("15652712315");
	// list.add(tp);
	// tp = new TFamilyphone();
	// tp.setOperation("2");
	// tp.setFamilyphone("15652712316");
	// list.add(tp);
	// tp = new TFamilyphone();
	// tp.setOperation("2");
	// tp.setFamilyphone("15652712315");
	// list.add(tp);
	// System.out.println(list.size());
	// Set<TFamilyphone> ts = new HashSet<TFamilyphone>();
	// ts.addAll(list);
	//
	// for (TFamilyphone student : ts) {
	// System.out.println(student.getFamilyphone());
	// }
	// List<TFamilyphone> result = new ArrayList<TFamilyphone>();
	// result.addAll(ts);
	// System.out.println(result.size());
	// }
	public List<TFamilyphone> getPhonelist() {
		List<TFamilyphone> list = new ArrayList<TFamilyphone>();
		Set<String> newset = RedisUtil.getInstance().getHashKeys(
				RedisKeyConstant.FAMILYPHONE_NEW+DateUtil.getFormatDate(new Date(), "yyyy-MM-dd"));
		int i = 0;
		for (String newkey : newset) {
			String newp = RedisUtil.getInstance().getHashKeyValue(
					RedisKeyConstant.FAMILYPHONE_NEW+DateUtil.getFormatDate(new Date(), "yyyy-MM-dd"), newkey);
			if (newp != null && newp.length() > 0) {
				TFamilyphone phone = (TFamilyphone) GsonUtils.getInstance()
						.fromJson(newp, TFamilyphone.class);
				if (phone.getFamilyphone() != null
						&& phone.getFamilyphone().length() > 0) {
					phone.setOperation("1");
					list.add(phone);
					String oldphone = RedisUtil.getInstance().getHashKeyValue(
							RedisKeyConstant.FAMILYPHONE_OLD+DateUtil.getFormatDate(new Date(), "yyyy-MM-dd"),
							phone.getNumber() + i);
					i = i + 1;
					if (oldphone != null && oldphone.length() > 0) {
						TFamilyphone oldtfamilyphone = new TFamilyphone();
						oldtfamilyphone.setFamilyphone(oldphone);
						oldtfamilyphone.setOperation("2");
						oldtfamilyphone.setNumber(phone.getNumber());
						oldtfamilyphone.setTime(phone.getTime());
						list.add(oldtfamilyphone);
					}

				}
			}
		}
		return list;

	}

	/***
	 * 上传文件
	 */
	public void upload() {
		try {
			File fp = new File(ConfigUtil.getProperty("ftp", "uploads"));
			File[] list = fp.listFiles();
			for (int i = 0; i < list.length; i++) {
				String filepath = fp.getPath() + File.separator
						+ list[i].getName();
				File f = new File(filepath);
				FileInputStream in = new FileInputStream(f);
				boolean flag = FtpUtil
						.uploadFile(ConfigUtil.getProperty("ftp", "url"),
								Integer.parseInt(ConfigUtil.getProperty("ftp",
										"port")), ConfigUtil.getProperty("ftp",
										"username"), ConfigUtil.getProperty(
										"ftp", "password"), ConfigUtil
										.getProperty("ftp", "uppath"), list[i]
										.getName(), in);
				if (flag) {
					copy(filepath, ConfigUtil.getProperty("ftp", "temp")
							+ File.separator + list[i].getName());
				}
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

	}

	public void copy(String path, String copyPath) {
		File filePath = new File(path);
		DataInputStream read;
		DataOutputStream write;
		if (filePath.isDirectory()) {
			File[] list = filePath.listFiles();
			for (int i = 0; i < list.length; i++) {
				String newPath = path + File.separator + list[i].getName();
				String newCopyPath = copyPath + File.separator
						+ list[i].getName();
				copy(newPath, newCopyPath);
			}
		} else if (filePath.isFile()) {
			try {
				read = new DataInputStream(new BufferedInputStream(
						new FileInputStream(path)));
				write = new DataOutputStream(new BufferedOutputStream(
						new FileOutputStream(copyPath)));
				String s = IOUtils.toString(read, "utf-8");
				IOUtils.write(s, write);
				read.close();
				write.close();
				System.out.println(path + "---OK!");
				// 删除原文件
				filePath.delete();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			System.out.println("文件路径不正确");
		}
	}
}
